const app = getApp()
var api = require('../../api/api')

Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        banner: [],
        channel: [],
        layout1: [],
        layout2: [],
        brand: [],
        newGoods: [],
        around: []
    },
    //事件处理函数
    bindViewTap: function () {
        wx.navigateTo({
            url: '../logs/logs'
        })
    },
    onShareAppMessage: function () {
        return {
            title: 'XMall',
            desc: 'XMall小程序商城',
            path: '/pages/index/index'
        }
    },
    onLoad: function () {
        this.getHomeGoods();
    },
    toSearch: function () {
        wx.navigateTo({
            url: '/pages/search/search'
        });
    },
    bannerNav: function (e) {
        let banner = e.target.dataset.value;
        if (banner.type === 0) {
            wx.navigateTo({
                url: '/pages/goods/goods?id=' + banner.linkId,
            })
        } else if (banner.type === 1) {
            wx.navigateTo({
                url: '/pages/promotion/promotion?title=' + banner.bannerName,
            })
        }
    },
    getHomeGoods() {//获取首页商品
        api.home().then(res => {
            this.filterData(res.result)
        });
    },
    filterData(data = []) {
        if (!Array.isArray(data)) {
            return;
        }

        let key = ''
        let obj = null;
        data.forEach(ele => {
            obj = {};
            key = ''

            switch (ele.name) {
            case '轮播图':
                key = 'banner'
                break;
            case '热门商品':
                key = 'brand'
                break;
            case '活动版块':
                key = 'layout1'
                break;
            case '官方精选':
                key = 'newGoods'
                break;
            case '活动版块2':
                key = 'layout2'
                break;
            case '品牌周边':
                key = 'around'
                break;
            default:
                break;
            }

            if (key) {
                obj[key] = ele.panelContents
                this.setData(obj);
            }
        });

        console.log(this.data);
    },
    channelNav: function (e) {
        let channel = e.target.dataset.value;

        if (channel.type === 0) {
            wx.navigateTo({
                url: '/pages/goods/goods?id=' + channel.linkId,
            });
        } else if (channel.type === 1) {
            wx.navigateTo({
                url: '/pages/promotion/promotion?title=' + channel.name,
            });
        }
    }
})
